﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Retrofit.Library;

namespace Retrofit.Input
{
    public class RumbleManager : GameComponent
    {
        private List<RumbleEntry> m_rumbleList = new List<RumbleEntry>();

        public RumbleManager(Game game)
            : base(game)
        {
        }

        private class RumbleEntry
        {
            public PlayerIndex Player;
            public RumbleSetting Setting;

            public RumbleEntry(PlayerIndex playerIndex, RumbleSetting setting)
            {
                Player = playerIndex;
                Setting = setting;
            }
        }

        public void AddRumble(PlayerIndex player, RumbleSetting rumbleSetting)
        {
            m_rumbleList.Add(new RumbleEntry(player, rumbleSetting));
        }

        public void Clear()
        {
            m_rumbleList.Clear();
        }

        public override void Update(GameTime gameTime)
        {
            int count = m_rumbleList.Count;
            
            for (int i = 0; i < count; i++)
            {
               RumbleEntry entry = m_rumbleList[i];

               GamePad.SetVibration(entry.Player, 
                   entry.Setting.LeftMotor, 
                   entry.Setting.RightMotor);

               entry.Setting.Miliseconds -= gameTime.ElapsedGameTime.Milliseconds;

               if (entry.Setting.Miliseconds <= 0)
               {
                   m_rumbleList.RemoveAt(i);
                   GamePad.SetVibration(entry.Player, 0f, 0f);
               }
            }

            base.Update(gameTime);
        }
    }
}
